<template>
  <view class="wrapper">
    <view class="tabsBox">
      <u-tabs
          :list="tabsList"
          lineWidth="50rpx"
          lineColor="#FF4400"
          :activeStyle="{
					color: '#333333',
					fontWeight: 'bold',
					fontSize: '30rpx'
				}"
          :inactiveStyle="{
					color: '#666666',
					fontWeight: 'bold',
					fontSize: '30rpx'
				}"
          :current="current"
          @click="tabsClick"
      ></u-tabs>
    </view>
    <!-- <u-refresh-complete ref="uRefreshComplete"/> -->
    <view class="main">
      <view class="" v-if="current === 0">
        <view class="goods">
          <u-empty v-if="!loading && goodsList.length === 0" mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" text="暂无商品"></u-empty>
          <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
            <image class="goods-item-img" :src="item.product_image" mode="aspectFill"></image>
            <view class="goods-item-name">
              {{ item.product_name }}
            </view>
            <view class="goods-item-btn" @click="orderNow(item)">
              立即进货
              <u-icon name="arrow-right" color="#fff" size="38rpx"></u-icon>
            </view>
          </view>
        </view>
        <!-- 加载更多 -->
        <u-loadmore :status="loadStatus" :loading-text="loadingText" :loadmore-text="loadmoreText" :nomore-text="nomoreText" v-if="goodsList.length > 0" />
      </view>
      <view class="inventory" v-if="current === 1">
        <u-empty v-if="!inventoryLoading && inventoryList.length === 0" mode="data" text="暂无库存商品"></u-empty>
        <view class="inventory-item" v-for="(item, index) in inventoryList" :key="item.id">
          <view class="inventory-item-time">
            <view class="inventory-item-index">
              {{ index + 1 }}
            </view>
            创建时间: {{ item.create_time || '--' }}
          </view>
          <view class="inventory-item-name">
            {{ item.product_name || '--' }}
            <view class="inventory-item-label" v-if="item.is_insured">已投保</view>
          </view>
          <view class="inventory-item-text">规格: {{ item.spec_name || '--' }}</view>
          <view class="inventory-item-text">期数: {{ item.lease_term || '--' }}期</view>
          <view class="inventory-item-text" style="margin-bottom: 0">价格: ￥{{ item.price || '0.00' }}</view>
          <view class="inventory-item-box">
            <view class="inventory-item-box-status">
              {{ getStatusText(item.leasing_status) }}
            </view>
            <view class="inventory-item-box-day" v-if="item.lease_days">
              {{ item.lease_days }}
              <text>天</text>
            </view>
          </view>
          <view class="inventory-item-footer">
            <view class="inventory-item-footer-item btnOne">立即提现</view>
            <view class="inventory-item-footer-item btnTwo">再次委托</view>
          </view>
        </view>
        <u-loadmore :status="loadStatus" :loading-text="loadingText" :loadmore-text="loadmoreText" :nomore-text="nomoreText" />
      </view>
    </view>
  </view>
</template>

<script>
import { product as productApi } from '@/api';
import { getInventoryList } from '@/api/modules/rental';

export default {
  onReachBottom() {
    if (this.current === 0) {
      if (this.loading || this.finished) return;
      this.loadStatus = 'loading';
      this.page++;
      this.fetchProducts();
    } else {
      if (this.inventoryLoading || this.inventoryFinished) return;
      this.loadStatus = 'loading';
      this.inventoryPage++;
      this.fetchInventoryList();
    }
  },
  data() {
    return {
      current: 0,
      tabsList: [
        {
          name: '商品进货'
        },
        {
          name: '我的库存'
        }
      ],
      // 商品列表相关
      goodsList: [],
      // 库存列表相关
      inventoryList: [],
      inventoryPage: 1,
      inventoryTotal: 0,
      inventoryLoading: false,
      inventoryFinished: false,
      // 分页相关
      page: 1,
      list_rows: 10,
      loading: false,
      loadStatus: 'loadmore',
      loadingText: '正在加载...',
      loadmoreText: '上拉加载更多',
      nomoreText: '没有更多了',
      finished: false
    };
  },
  onLoad() {
    this.fetchProducts();
  },
  async onPullDownRefresh() {
    if (this.current === 0) {
      this.page = 1;
      this.finished = false;
      this.loadStatus = 'loadmore';
      await this.fetchProducts();
      uni.stopPullDownRefresh();
    } else {
      this.inventoryPage = 1;
      this.inventoryFinished = false;
      this.loadStatus = 'loadmore';
      await this.fetchInventoryList();
      uni.stopPullDownRefresh();
    }

    if (this.refreshing) {
      uni.stopPullDownRefresh();
      this.refreshing = false;
    }
  },
  watch: {
    current(newVal) {
      if (newVal === 1 && this.inventoryList.length === 0) {
        this.fetchInventoryList();
      }
    }
  },
  methods: {
    orderNow(item) {
      uni.navigateTo({
        url: `/package-purse/orderNow/orderNow?id=${item.product_id}`
      });
    },
    tabsClick(item) {
      this.current = item.index;
    },
    // 获取库存列表
    async fetchInventoryList() {
      if (this.inventoryLoading) return;

      this.inventoryLoading = true;
      this.loadStatus = 'loading';

      try {
        const params = {
          page: this.inventoryPage,
          list_rows: this.list_rows,
          leasing_status: '0' // 默认查询在库商品
        };

        const { data } = await getInventoryList(params);
        const items = data?.data || [];

        if (this.inventoryPage === 1) {
          this.inventoryList = items;
        } else {
          this.inventoryList = [...this.inventoryList, ...items];
        }

        this.inventoryTotal = data.total || 0;

        // 判断是否还有更多数据
        if (items.length < this.list_rows || this.inventoryList.length >= this.inventoryTotal) {
          this.inventoryFinished = true;
          this.loadStatus = 'nomore';
        } else {
          this.loadStatus = 'loadmore';
        }
      } catch (error) {
        console.error('获取库存列表失败:', error);
        uni.showToast({
          title: '获取库存列表失败',
          icon: 'none'
        });
        this.loadStatus = 'loadmore';
        uni.stopPullDownRefresh();
      } finally {
        this.inventoryLoading = false;
      }
    },
    async fetchProducts() {
      if (this.loading) return;

      this.loading = true;
      if (this.page === 1) {
        this.goodsList = [];
      }

      try {
        const params = {
          page: this.page,
          list_rows: this.list_rows,
          app_id: this.getAppId && this.getAppId() ? this.getAppId() : 10001
        };

        const { data } = await productApi.getProductList(params);
        const newItems = Array.isArray(data?.data) ? data?.data : [];

        if (this.page === 1) {
          this.goodsList = newItems;
        } else {
          this.goodsList = [...this.goodsList, ...newItems];
        }

        this.total = data.total || 0;

        // 判断是否还有更多数据
        if (newItems.length < this.list_rows || this.goodsList.length >= this.total) {
          this.finished = true;
          this.loadStatus = 'nomore';
        } else {
          this.loadStatus = 'loadmore';
        }
      } catch (e) {
        console.error('获取商品列表失败', e);
        this.loadStatus = 'loadmore';
        uni.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '待出租',
        1: '匹配中',
        2: '出租中',
        3: '已退机',
        4: '半路退机',
        5: '已完结'
      };
      return statusMap[status] || '--';
    }
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  padding: 0 30rpx 30rpx;
}

.tabsBox {
  padding: 10rpx 70rpx 0 70rpx;

  ::v-deep .u-tabs__wrapper__nav__item {
    width: 50%;
    box-sizing: border-box;
  }
}

.main {
  padding: 20rpx 0rpx;
}

.goods {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;

  &-item {
    width: 47.5%;
    margin-bottom: 30rpx;
    background: #ffffff;
    border-radius: 10rpx;

    &-img {
      margin: 0 auto;
      width: 330rpx;
      height: 330rpx;
      border-radius: 10rpx 10rpx 0 0;
    }

    &-name {
      margin: 30rpx 0;
      text-align: center;
      font-family: 'PingFang SC';
      font-weight: bold;
      font-size: 28rpx;
      color: #333333;
    }

    &-btn {
      font-family: 'PingFang SC';
      font-weight: bold;
      font-size: 36rpx;
      color: #ffffff;
      height: 89rpx;
      background: #ff4400;
      border-radius: 0 0 10rpx 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.inventory {
  &-item {
    position: relative;
    padding: 30rpx 0;
    background: #ffffff;
    border-radius: 14rpx;
    margin-bottom: 20rpx;
    font-family: 'PingFang SC';
    font-weight: 400;
    font-size: 24rpx;
    color: #999999;

    &-time {
      display: flex;
      align-items: center;
    }

    &-index {
      width: 67rpx;
      height: 32rpx;
      background: rgba(255, 68, 0, 0.1);
      border-radius: 0 6rpx 6rpx 0;
      line-height: 32rpx;
      text-align: center;
      font-family: 'PingFang SC';
      font-weight: 500;
      font-size: 26rpx;
      color: #ff0000;
      margin-right: 20rpx;
    }

    &-name {
      display: flex;
      align-items: center;
      padding-left: 30rpx;
      font-family: 'PingFang SC';
      font-weight: 500;
      font-size: 30rpx;
      color: #333333;
      margin: 30rpx 0;
    }

    &-text {
      margin-bottom: 30rpx;
      padding-left: 30rpx;
      font-family: 'PingFang SC';
      font-weight: 400;
      font-size: 24rpx;
      color: #999999;
    }

    &-label {
      margin-left: 10rpx;
      padding: 2rpx;
      background: rgba(255, 109, 56, 0.8);
      border-radius: 4rpx;
      font-family: 'PingFang SC';
      font-weight: 400;
      font-size: 22rpx;
      color: #ffffff;
    }

    &-box {
      position: absolute;
      top: 30rpx;
      right: 55rpx;

      &-status {
        font-family: 'PingFang SC';
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
      }

      &-day {
        margin-top: 30rpx;
        display: flex;
        align-items: center;
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 36rpx;
        color: #333333;

        text {
          margin-left: 5rpx;
          font-weight: 400;
          font-size: 24rpx;
          color: #333333;
        }
      }
    }

    &-footer {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 14rpx;
      padding-right: 20rpx;

      &-item {
        width: 140rpx;
        height: 50rpx;
        border-radius: 6rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .btnOne {
        background: rgba(255, 68, 0, 0.1);
        font-family: 'PingFang SC';
        font-weight: 500;
        font-size: 24rpx;
        color: #ff4603;
      }

      .btnTwo {
        background: #ff4400;
        font-family: 'PingFang SC';
        font-weight: 500;
        font-size: 24rpx;
        color: #ffffff;
        margin-left: 20rpx;
      }
    }
  }
}
</style>
